package com.horay.nettydemo.nio.file;

import javafx.scene.control.Spinner;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.function.BiPredicate;

/**
 * 拷贝文件
 *
 * @author heyingcheng
 * @date 2019/11/23 21:10
 */
@Slf4j
public class CopyFileByTransfer {

    private static final String FROM_PATH_NAME = "D:/root/cctv-support-logs/support-gsnw-8080/logs/catalina/catalina.2019-09-20.log";
    private static final String TO_PATH_NAME_01 = "D:/root/cctv-support-logs/support-gsnw-8080/logs/catalina/catalina.2019-09-20-copy-03.log";
    private static final String TO_PATH_NAME_02 = "D:/root/cctv-support-logs/support-gsnw-8080/logs/catalina/catalina.2019-09-20-copy-04.log";

    public static void main(String[] args) {
        File fromFile = new File(FROM_PATH_NAME);

        transfer(fromFile, new File(TO_PATH_NAME_01), (fromChannel, toChannel) -> {
            try {
                fromChannel.transferTo(0, fromChannel.size(), toChannel);
            } catch (IOException e) {
                log.error("拷贝文件异常", e);
            }
            return true;
        });

        transfer(fromFile, new File(TO_PATH_NAME_02), (fromChannel, toChannel) -> {
            try {
                toChannel.transferFrom(fromChannel, 0, fromChannel.size());
            } catch (IOException e) {
                log.error("拷贝文件异常", e);
            }
            return true;
        });
    }

    private static void transfer(File fromFile, File toFile, BiPredicate<FileChannel, FileChannel> biPredicate) {
        try (FileInputStream fileInputStream = new FileInputStream(fromFile);
             FileOutputStream fileOutputStream= new FileOutputStream(toFile);
             FileChannel fromChannel = fileInputStream.getChannel();
             FileChannel toChannel = fileOutputStream.getChannel()) {
            biPredicate.test(fromChannel, toChannel);
        } catch (FileNotFoundException e) {
            log.error("拷贝文件异常", e);
        } catch (IOException e) {
            log.error("拷贝文件异常", e);
        }
    }

}
